﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using System.Collections.Generic;
using SmartProject.BusinessObjects;

namespace SmartProject.AppSpace
{
    public partial class MyPage : UI.BasePage, UI.IDataSourcePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (UI.BasePage.IsFirstTimePreferenceSetup)
                {
                    Log("Page_Load", "This is a new install. We will redirect the user to setup the application.", "Info");
                    Response.Redirect("~/AppSpace/Setup.aspx");
                }
                else
                {
                    if (UI.BasePage.IsFirstTimeUserSetup)
                    {
                        Response.Redirect("~/AppSpace/Users.aspx");
                    }
                    else
                    {
                        // Check if sprint/ product list are empty.
                        if (base.IsFirstTimeManagementSetup)
                        {
                            Response.Redirect("~/AppSpace/Management.aspx");
                        }
                        else
                        {
                            if (!Page.IsPostBack)
                            {
                                this.SetPage("Homepage", "Your Homepage gives you the option view work items that are related to you which are either assigned to you or which you are the owner of.");
                                string stringValue;
                                int intValue;
                                GetPreference(this.DrpViewOptions.ID, out stringValue, out intValue);
                                if (!String.IsNullOrEmpty(stringValue))
                                {
                                    this.DrpViewOptions.SelectedValue = stringValue;
                                }
                                WorkGridView1.RefreshView(false);
                                RefreshUserMessages(new UserMessage());
                            }
                        }
                    }
                }
            }
            else
            {
                Response.Redirect("~/Default.aspx", true);
            }
        }

        private void RefreshUserMessages(UserMessage userMessage)
        {
            userMessage.SetAttribute("UserId", base.UserId);
            System.Data.DataTable messages = userMessage.LoadUnReadUserMessages();
            if (messages != null && messages.Rows.Count > 0)
            {
                this.LstUserMessages.DataSource = messages;
                this.LstUserMessages.DataBind();

                foreach (ListViewDataItem message in this.LstUserMessages.Items)
                {
                    Label lbl = (Label)message.FindControl("LblDescription");
                    if (lbl.Text.Length > 250)
                    {
                        lbl.Text = lbl.Text.Substring(0, 250) + "...";
                    }
                }

                this.PopUserMessages.Show();
            }
            else
            {
                this.LstUserMessages.DataSource = null;
                this.LstUserMessages.DataBind();
                //this.BtnShow.Visible = false;
            }
        }

        protected void BtnMarkAsRead_Click(object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)sender;
            UserMessage userMessage = new UserMessage();
            userMessage.SetAttribute("MessageId", btn.CommandArgument);
            userMessage.SetAttribute("UserId", base.UserId);
            userMessage.Update();
            RefreshUserMessages(userMessage);
        }

        protected void BtnView_Click(object sender, EventArgs e)
        {
            LinkButton btnView = (LinkButton)sender;

            LinkButton btnMarkAsRead = (LinkButton)btnView.Parent.FindControl("BtnMarkAsRead");
            UserMessage userMessage = new UserMessage();
            userMessage.SetAttribute("MessageId", btnMarkAsRead.CommandArgument);
            userMessage.SetAttribute("UserId", base.UserId);
            userMessage.Update();

            Cache["WorkID"] = btnView.CommandArgument;
            Response.Redirect("~/AppSpace/Work.aspx", true);
        }

        #region IDataSourcePage Members

        DataTable SmartProject.UI.IDataSourcePage.DataSource
        {
            get
            {
                Work work = new Work();
                string conditional;
                if (String.IsNullOrEmpty(this.TxtSearch.Text))
                {
                    if (this.DrpViewOptions.SelectedValue == "1")
                    {
                        // Work assigned to me.
                        conditional = String.Format(" wrk.[DeveloperId] = {0} ", base.UserId);
                    }
                    else if (this.DrpViewOptions.SelectedValue == "2")
                    {
                        // Work assigned to others that belonges to me.
                        conditional = String.Format(" wrk.[OwnerId] = {0} ", base.UserId);
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    bool numbersOnly = true;
                    // To prevent SQL injection attacks, we validate the search text. It cannot contain symbols.
                    System.Text.StringBuilder search = new System.Text.StringBuilder();
                    foreach (Char c in this.TxtSearch.Text)
                    {
                        if (Char.IsLetterOrDigit(c))
                        {
                            search.Append(c);
                            if (Char.IsLetter(c))
                            {
                                numbersOnly = false;
                            }
                        }
                    }
                    string searchText = search.ToString();
                    System.Text.StringBuilder text = new System.Text.StringBuilder();

                    text.Append(String.Format(" (wrk.[Description] LIKE '%{0}' ", searchText));
                    text.Append(String.Format("OR wrk.[Description] LIKE ' %{0}% ' ", searchText));
                    text.Append(String.Format("OR wrk.[Description] LIKE '{0}%' ", searchText));
                    text.Append(String.Format("OR wrk.[Description] LIKE '%{0}%' ", searchText));
                    if (numbersOnly)
                    {
                        text.Append(String.Format("OR wrk.[WorkId] = {0}) ", searchText));
                    }
                    else
                    {
                        text.Append(") ");
                    }
                    conditional = text.ToString();
                }

                if (!this.ChkShowApproved.Checked)
                {
                    System.Text.StringBuilder text = new System.Text.StringBuilder(conditional);
                    text.Append(" AND wrk.[StatusId] <> ");
                    text.Append(work.Statuses.GetId("Approved", false));
                    text.Append(" ");
                    conditional = text.ToString();
                }

                string orderBy = String.Empty;
                switch (this.DrpOrdering.SelectedValue)
                {
                    case "0":
                        orderBy = "wrk.[Created]";
                        break;

                    case "1":
                        orderBy = "wrk.[PrioritySeverityId]";
                        break;

                    case "2":
                        orderBy = "wrk.[DueDate]";
                        break;
                }
                return work.LoadWorks(conditional, orderBy, (this.DrpDescAsc.SelectedIndex == 0));
            }
        }

        void SmartProject.UI.IDataSourcePage.Refresh()
        {
            WorkGridView1.RefreshView(false);
        }

        #endregion

        public override void RefreshPage(object obj)
        {
            // Do nothing.
        }

        public override AjaxControlToolkit.ModalPopupExtender Popup(string name)
        {
            return this.WorkGridView1.Popup;
        }

        protected void BtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            SavePreference(this.DrpViewOptions.ID, this.DrpViewOptions.SelectedValue, -1);
            WorkGridView1.RefreshView(false);
        }
    }
}
